/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Validator;

import dao.UserDAO;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author amkreuz
 */
@FacesValidator("Validator.UserNameValidator")
public class UserNameValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        try {
            UserDAO.init();
            List<String> userNames = UserDAO.getAllUserNames();
            if (userNames.contains(value.toString())) {
                FacesMessage msg = new FacesMessage("User Name Already exist");
                throw new ValidatorException(msg); 
            }
 
            
            
        } catch (SQLException ex) {
            Logger.getLogger(UserNameValidator.class.getName()).log(Level.SEVERE, null, ex);
            FacesMessage msg = new FacesMessage("User Name Already exist");
            throw new ValidatorException(msg); 
        }
        finally {
            try {
                UserDAO.terminate();
            } catch (SQLException ex) {
                Logger.getLogger(UserNameValidator.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
}
